package com.itheima.controller.admin;


import com.itheima.common.constant.MessageConstant;
import com.itheima.common.entity.PageResult;
import com.itheima.common.entity.QueryPageBean;
import com.itheima.common.entity.Result;
import com.itheima.common.utils.AliOssUtil;
import com.itheima.exception.SetMealException;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetMealService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/setmeal")
@Slf4j
@Api(tags = "套餐管理")
@RequiredArgsConstructor
public class SetMealController {
    private final SetMealService setMealService;
    private final AliOssUtil aliOssUtil;
    private final RedisTemplate redisTemplate;

    /**
     * 添加套餐
     *
     * @param checkgroupIds
     */
    @PostMapping("/add")
    @ApiOperation("添加套餐")
    public Result addCheckGroup(
            @RequestBody Setmeal setmeal,
            @RequestParam String checkgroupIds
    ) {
        log.info("添加套餐:{}", setmeal);
        log.info("checkitemIdsStr: {}", checkgroupIds);
        // 将字符串转换为 Integer 列表
        List<Integer> ids = convertToIntegerList(checkgroupIds);
        Result result = new Result();
        try {
            setMealService.addSetMeal(setmeal, ids);
            redisTemplate.opsForSet().add("JunkPhotos"+":"+MessageConstant.ADD_KEY,setmeal.getImg());
        } catch (Exception e) {
            result.setFlag(false);
            result.setMessage(MessageConstant.ADD_SETMEAL_FAIL);
            return result;
        }
        result.setFlag(true);
        result.setMessage(MessageConstant.ADD_SETMEAL_SUCCESS);
        return result;
    }
    /**
     * 套餐分页查询
     *
     * @param queryPageBean
     * @return
     */
    @PostMapping("/findPage")
    @ApiOperation("套餐分页查询")
    public PageResult pageQuery(@RequestBody QueryPageBean queryPageBean) {
        log.info("套餐分页查询:{}", queryPageBean);
        return setMealService.pageQuery(queryPageBean);
    }
    @GetMapping("/findById")
    @ApiOperation("根据Id查询套餐")
    public Result findByIdSetMeal(Integer id) {
        log.info("查询套餐:{}", id);
        Result result = new Result();
        try {
            Setmeal setMeal = setMealService.findByIdSetMeal(id);
            result.setData(setMeal);
        } catch (Exception e) {
            throw new SetMealException(MessageConstant.QUERY_SETMEAL_FAIL);
        }
        result.setFlag(true);
        result.setMessage(MessageConstant.QUERY_SETMEAL_SUCCESS);
        return result;
    }
    /**
     * 文件上传
     * @param imgFile
     * @return
     */
    @PostMapping("/upload")
    @ApiOperation("文件上传")
    public Result upload(@RequestBody MultipartFile imgFile){
        log.info("文件上传，{}",imgFile);
        Result result = new Result();
        try {
            String originalFilename = imgFile.getOriginalFilename();
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String objectName = UUID.randomUUID().toString()+extension;
            String filePath = aliOssUtil.upload(imgFile.getBytes(), objectName);
            //通过redis的set保存到redis
            redisTemplate.opsForSet().add("JunkPhotos"+":"+MessageConstant.UPLOAD_KEY, filePath);
            result.setData(filePath);
        } catch (IOException e) {
            throw new SetMealException(MessageConstant.PIC_UPLOAD_FAIL);
        }
        result.setFlag(true);
        result.setMessage(MessageConstant.PIC_UPLOAD_SUCCESS);
        return result;
    }
    /**
     * 套餐修改
     * @param setmeal
     * @return
     */
    @PostMapping("/edit")
    @ApiOperation("套餐修改")
    public Result updateSetMeal(
            @RequestBody Setmeal setmeal,
            @RequestParam String checkGroupIds
    ){
        log.info("套餐修改:{}", setmeal);
        log.info("checkitemIdsStr: {}", checkGroupIds);
        List<Integer> ids = convertToIntegerList(checkGroupIds);
        Result result = new Result();
        try {
            setMealService.updateSetMeal(setmeal, ids);
        }
        catch (SetMealException e) {
            result.setFlag(false);
            result.setMessage(MessageConstant.EDIT_SETMEAL_FAIL);
            return result;
        }
        result.setFlag(true);
        result.setMessage(MessageConstant.EDIT_SETMEAL_SUCCESS);
        return result;
    }



    // 添加通用ID转换方法
    private List<Integer> convertToIntegerList(String idsStr) {
        List<Integer> ids = new ArrayList<>();
        if (idsStr != null && !idsStr.isEmpty()) {
            for (String id : idsStr.split(",")) {
                try {
                    ids.add(Integer.parseInt(id.trim()));
                } catch (NumberFormatException e) {
                    log.error("无效的ID格式: {}", id);
                }
            }
        }
        return ids;
    }
}
